#extension GL_EXT_gpu_shader4 : enable
#extension GL_ARB_texture_rectangle : enable 

uniform sampler2DRect unshotVectorsSampler;
uniform sampler2DRect fovVisibilityVectorSampler;
uniform sampler2DArray facePositionsSampler;
uniform sampler2D shooterDeltaBjSampler;

uniform int shooterId;
uniform vec2 shooterDeltaBjTexCoords;
uniform int shooterLevel;
uniform int unshotShooterLevel;

void main(void)
{
	ivec2 textureIndex = ivec2(gl_TexCoord[0].st);
	int elementIndex = textureIndex.x - 1;
	int receiverIndex = textureIndex.y - 1;
	ivec2 shooterUnshotTextureSize = textureSize2DArray(facePositionsSampler, unshotShooterLevel).xy;
	int shooterUnshotTextureArea = shooterUnshotTextureSize.x * shooterUnshotTextureSize.y;

	int shooterColumnsStartIndex = shooterId * shooterUnshotTextureArea;
	ivec2 scaledDeltaBjTexCoords = ivec2(floor(vec2(shooterUnshotTextureSize.x * shooterDeltaBjTexCoords.x, shooterUnshotTextureSize.y * shooterDeltaBjTexCoords.y)));
	int shooterElementCoords = scaledDeltaBjTexCoords.x + (scaledDeltaBjTexCoords.y * shooterUnshotTextureSize.x);
	int shooterElementIndex = shooterColumnsStartIndex + shooterElementCoords;

	vec4 unshotVectors = texture2DRect(unshotVectorsSampler, gl_TexCoord[0].st);

	bool isNotCurrentShooterElementAndNotVisibilityColumn = (elementIndex != shooterElementIndex) && (textureIndex.x != 0);
	if(isNotCurrentShooterElementAndNotVisibilityColumn)
	{
		//The only column that this shader writes to for each pass is the current shooter's column, with the
		//exception of the first column visibility boolean vector.
		gl_FragColor = unshotVectors;
		return;
	}

	bool isShooterPositionsRow = textureIndex.y == 0;
	if(isShooterPositionsRow)
	{
		//Write out the center of the shooter face, to reconstruct the shot
		gl_FragColor = texture2DArrayLod(facePositionsSampler, vec3(shooterDeltaBjTexCoords, shooterId), float(unshotShooterLevel));
		return;
	}

	bool isVisible = texture2DRect(fovVisibilityVectorSampler, vec2(receiverIndex, 0));
	bool isVisibilityColumnAndFaceIsNotVisible = textureIndex.x == 0 && !isVisible;
	if(isVisibilityColumnAndFaceIsNotVisible)
	{
		gl_FragColor =  vec4(1, 1, 1, 1);
		return;
	}

	if(!isVisible)
	{
		gl_FragColor = unshotVectors + texture2DLod(shooterDeltaBjSampler, shooterDeltaBjTexCoords, float(shooterLevel));
		return;
	}

	gl_FragColor = unshotVectors;
}

